<script lang="ts" setup>
import { TooltipPositioningOption } from '@fluentui/web-components';

type TooltipPosition = keyof typeof TooltipPositioningOption;

const props = withDefaults(
  defineProps<{
    /**
     * The ID of the anchor element for the tooltip
     */
    anchor?: string;

    /**
     * Content text of the tooltip (alternative to using slot)
     */
    content?: string;

    /**
     * Delay time in milliseconds before showing/hiding the tooltip
     */
    delay?: number;

    /**
     * Alternative to anchor - automatically generate a unique ID for the trigger element
     */
    for?: string;

    /**
     * ID for the tooltip element
     */
    id?: string;

    /**
     * Positioning of the tooltip relative to the anchor element
     * Accepts both FluentUI positioning and common placement values
     */
    positioning?: TooltipPosition;
  }>(),
  {
    anchor: undefined,
    for: undefined,
    content: undefined,
    delay: 250,
    positioning: 'above',
    id: undefined,
  },
);

// Generate a unique ID for the anchor element if needed
const uniqueId = `tooltip-anchor-${Math.random().toString(36).slice(2, 11)}`;
const computedAnchorId = ref(props.anchor || props.for || uniqueId);
const tooltipRef = ref<HTMLElement>();
const triggerRef = ref<HTMLElement>();

// Set up the tooltip after all components are mounted
onMounted(async () => {
  await nextTick();
  if (!props.anchor && !props.for && triggerRef.value) {
    triggerRef.value.id = computedAnchorId.value;

    if (tooltipRef.value) {
      tooltipRef.value.setAttribute('anchor', computedAnchorId.value);

      // Set the content if provided
      if (props.content) {
        tooltipRef.value.textContent = props.content;
      }

      // Set the ID if provided
      if (props.id) {
        tooltipRef.value.id = props.id;
      }
    }
  } else {
    // For the direct usage case where the tooltip is used independently
    if (tooltipRef.value) {
      // Set the content if provided
      if (props.content) {
        tooltipRef.value.textContent = props.content;
      }

      // Set the ID if provided
      if (props.id) {
        tooltipRef.value.id = props.id;
      }
    }
  }
});
</script>

<template>
  <span>
    <fluent-tooltip
      ref="tooltipRef"
      :anchor="computedAnchorId"
      :positioning="positioning"
      :delay="delay"
      :id="id"
    >
      {{ content }}
    </fluent-tooltip>
    <span ref="triggerRef" :id="computedAnchorId">
      <slot></slot>
    </span>
  </span>
</template>

<style scoped></style>
